In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
# Load pickled data
import pickle
import numpy as np
from sklearn.utils import shuffle
# TODO: Fill this in based on where you saved the training and testing data
training_file = './data/train.p'
validation_file= './data/valid.p'
testing_file = './data/test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test_origin = test['features'], test['labels']
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
y_test_origin[0]
import pandas as pd
classLabelList = pd.read_csv('signnames.csv')
classLabelList.keys()
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = X_train.shape[0]
# TODO: Number of validation examples
n_validation = X_valid.shape[0]
# TODO: Number of testing examples.
n_test = X_test.shape[0]
# TODO: What's the shape of an traffic sign image?
image_shape = X_train.shape[1:]
# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(y_train))
print("Number of training examples =", n_train)
print("Number of testing examples =", n_validation)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?
### Count the instance number for difference classes.
unique_class, unique_count = np.unique(y_train, return_counts=True)
train_sortedLabels = np.argsort(unique_count)
unique_class_test, unique_count_test = np.unique(y_test, return_counts=True)
test_sortedLabels = np.argsort(unique_count_test)
print(unique_count)
print(train_sortedLabels[unique_class])
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline
# draw the max size picture for training and testing
print("Top Three Maximum count Samples:")
fg, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 10))
class_id = train_sortedLabels[-1]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax1.imshow(X_train[train_index])
ax1.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==class_id].SignName.to_string(header=False,index=False)
ax1.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription: %s'%(class_id, train_description), fontsize=8)
class_id = train_sortedLabels[-2]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax2.imshow(X_train[train_index])
ax2.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==y_train[train_index]].SignName.to_string(header=False,index=False)
ax2.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription: %s'%(class_id, train_description), fontsize=8)
class_id = train_sortedLabels[-3]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax3.imshow(X_train[train_index])
ax3.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==y_train[train_index]].SignName.to_string(header=False,index=False)
ax3.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription: %s'%(class_id, train_description), fontsize=8)
plt.setp([a.get_xticklabels() for a in fg.axes], visible=False)
plt.setp([a.get_yticklabels() for a in fg.axes], visible=False)
plt.show()
### We also plot bottom three least example images:
print("Bottom three least example images:")
fg, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 10))
class_id = train_sortedLabels[0]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax1.imshow(X_train[train_index])
ax1.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==class_id].SignName.to_string(header=False,index=False)
ax1.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription: %s'%(class_id, train_description), fontsize=8)
class_id = train_sortedLabels[1]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax2.imshow(X_train[train_index])
ax2.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==y_train[train_index]].SignName.to_string(header=False,index=False)
ax2.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription: %s'%(class_id, train_description), fontsize=8)
class_id = train_sortedLabels[2]
img_idx = np.where(y_train==class_id)
train_index = np.random.choice(img_idx[0])
ax3.imshow(X_train[train_index])
ax3.set_title('count: %d\n\n'%(unique_count[class_id]))
train_description = classLabelList[classLabelList.ClassId==y_train[train_index]].SignName.to_string(header=False,index=False)
ax3.text(-1.0,-2.0,'Training Set Sample ClassId: %d\nDescription: %s'%(class_id, train_description), fontsize=8)
plt.setp([a.get_xticklabels() for a in fg.axes], visible=False)
plt.setp([a.get_yticklabels() for a in fg.axes], visible=False)
plt.show()
### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.
def labelset_info(labelsettxt, dataset):
# get stats for the labels
labelset = dataset['labels']
labelStats = pd.DataFrame(labelset)
# print(labelsettxt, "set label stats:")
# print(labelStats.describe())
labelsInfo = {}
modeCount = 0
modeLabel = 0
for i in range(len(labelset)):
# for each label
label = str(labelset[i])
# try to see if there is a hash hit
labelInstance = labelsInfo.get(label, {'count': 0, 'samples':[]})
# add to the count
count = labelInstance['count'] + 1
# add to samples
samples = labelInstance['samples']
samples.append(i)
# put in the last Index
labelsInfo[label] = {'lastIdx':i, 'count': count, 'label':int(label), 'samples':samples}
# update most common size
if count > modeCount:
modeCount = count
modeSize = labelsInfo[label]
# get the list of counts and sort them
sortedLabels = list(labelsInfo.keys())
def compare_count(label):
return labelsInfo[label]['count']
sortedLabels.sort(key=compare_count)
# get the unique number of original picture sizes and the min and max last instance
n_labels = len(sortedLabels)
minLabel = sortedLabels[0]
maxLabel = sortedLabels[n_labels-1]
# print the stats
print("\nNumber of unique labels in", labelsettxt,"set: ", n_labels)
print("\nDistribution of", labelsettxt, "set labels:")
for n in range(n_labels):
i = sortedLabels[n_labels-n-1]
classId = labelsInfo[str(i)]['label']
index = labelsInfo[str(i)]['lastIdx']
count = labelsInfo[str(i)]['count']
description = classLabelList[classLabelList.ClassId==classId].SignName.to_string(header=False,index=False)
print(labelsettxt, " set count: {0:4d} ClassId: {1:02d} Description: {2}".format(count, classId, description))
return n_labels, sortedLabels, labelsInfo, minLabel, maxLabel, modeLabel
train_labels, train_sortedLabels, train_labelInfo, train_minLabel, train_maxLabel, train_modeLabel = labelset_info("training", train)
test_labels, test_sortedLabels, test_labelInfo, test_minLabel, test_maxLabel, test_modeLabel = labelset_info("testing", test)
from tqdm import tqdm
import time
from matplotlib import gridspec
def draw_sample_labelsets(datasettxt, sortedlabels, labeldata, dataset, n_samples=10, cmap=None):
n_labels = len(sortedlabels)
# size of each sample
fig = plt.figure(figsize=(n_samples*1.8, n_labels))
w_ratios = [1 for n in range(n_samples)]
w_ratios[:0] = [int(n_samples*0.8)]
h_ratios = [1 for n in range(n_labels)]
# gridspec
time.sleep(1) # wait for 1 second for the previous print to appear!
grid = gridspec.GridSpec(n_labels, n_samples+1, wspace=0.0, hspace=0.0, width_ratios=w_ratios, height_ratios=h_ratios)
labelset_pbar = tqdm(range(n_labels), desc=datasettxt, unit='labels')
for a in labelset_pbar:
classId = labeldata[str(sortedlabels[n_labels-a-1])]['label']
description = classLabelList[classLabelList.ClassId==classId].SignName.to_string(header=False,index=False)
count = labeldata[str(sortedlabels[n_labels-a-1])]['count']
for b in range(n_samples+1):
i = a*(n_samples+1) + b
ax = plt.Subplot(fig, grid[i])
if b == 0:
ax.annotate('ClassId %d (%d): %s'%(classId, count, description), xy=(0,0), xytext=(0.0,0.5))
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
else:
random_i = np.random.choice(labeldata[str(sortedlabels[n_labels-a-1])]['samples'])
image = dataset[random_i]
if cmap == None:
ax.imshow(image)
else:
# yuv = cv2.split(image)
# ax.imshow(yuv[0], cmap=cmap)
ax.imshow(image, cmap=cmap)
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
# hide the borders\
if a == (n_labels-1):
all_axes = fig.get_axes()
for ax in all_axes:
for sp in ax.spines.values():
sp.set_visible(False)
plt.show()
draw_sample_labelsets('Train set sample images (RGB)', train_sortedLabels, train_labelInfo, X_train)
draw_sample_labelsets('Test set sample images (RGB)', test_sortedLabels, test_labelInfo, X_test)
### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.
def my_reverse(list):
newlist = []
for n in list:
newlist[:0] = [n]
return newlist
# Plot bar graph of class id count distribution
n_labels = len(train_sortedLabels)
training_labels = my_reverse(train_sortedLabels)
training_counts = [train_labelInfo[n]['count'] for n in training_labels]
training_percantage = training_counts / np.sum(training_counts)
testing_counts = [test_labelInfo[n]['count'] for n in training_labels]
test_percantage = testing_counts / np.sum(testing_counts)
ind = np.arange(n_labels)
width = 0.35
fg, ax = plt.subplots(figsize=(n_labels/2, 10))
rects1 = ax.bar(ind+1, training_percantage, width, color='g')
rects2 = ax.bar(ind+1+width, test_percantage, width, color='r')
# add some text for labels, title and axes ticks
ax.set_ylabel("Percantage", fontsize=20)
ax.set_title("Percantage by datasets and class ids", fontsize=20)
ax.set_xticks(ind + width+1.0)
ax.set_xticklabels(training_labels, fontsize=12)
ax.set_xlabel("Class Id", fontsize=20)
ax.legend((rects1[0], rects2[0]), ('Training', 'Testing'))
plt.show()
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.
Other pre-processing steps are optional. You can try different techniques to see if it improves performance.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
X_train = (X_train - 128) / 128
X_valid = (X_valid - 128) / 128
X_test = (X_test - 128) / 128
from sklearn.utils import shuffle
X_train, y_train = shuffle(X_train, y_train)
### Define your architecture here.
### Feel free to use as many code cells as needed.
# Here we use LeNet 5 archecture
import tensorflow as tf
from models import LeNet
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
x = tf.placeholder(tf.float32, (None, 32, 32, 3))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, n_classes)
rate = 0.001
logits = LeNet(x, n_classes)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
# Model evaluation
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
total_accuracy += (accuracy * len(batch_x))
return total_accuracy / num_examples
EPOCHS = 100
BATCH_SIZE = 128
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
num_examples = len(X_train)
print("Training...")
print()
for i in range(EPOCHS):
X_train, y_train = shuffle(X_train, y_train)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train[offset:end], y_train[offset:end]
sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
training_accuracy = evaluate(X_train, y_train)
validation_accuracy = evaluate(X_valid, y_valid)
print("EPOCH {} ...".format(i+1))
print("Training Accuracy = {:.3f}".format(training_accuracy))
print("Validation Accuracy = {:.3f}".format(validation_accuracy))
print()
saver.save(sess, './lenet')
print("Model saved")
### Preprocess the data here.
###
### Step 1:
### According to the given paper, http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf
### We convert the data into YUV space using Y
import cv2
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
def RGB2YUV(image_data):
yuv_image_data = []
for i in range(len(image_data)):
yuv_image_data.append(cv2.cvtColor(image_data[i], cv2.COLOR_RGB2YUV))
return np.array(yuv_image_data)
X_train = RGB2YUV(X_train)
X_valid = RGB2YUV(X_valid)
X_test = RGB2YUV(X_test)
print('Features are now converted YUV!')
X_train.shape
f_mean = np.mean(X_train)
print(f_mean)
f_std = np.std(X_train)
print(f_std)
X_train = (X_train - f_mean) / f_std
X_valid = (X_valid - f_mean) / f_std
X_test = (X_test - f_mean) / f_std
X_train, y_train = shuffle(X_train, y_train)
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, n_classes)
rate = 0.001
logits = LeNet(x, input_channel=1, n_classes=n_classes)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
# Model evaluation
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()
# **Traffic Sign Recognition**
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
total_accuracy += (accuracy * len(batch_x))
return total_accuracy / num_examples
EPOCHS = 100
BATCH_SIZE = 128
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
num_examples = len(X_train)
print("Training...")
print()
for i in range(EPOCHS):
X_train, y_train = shuffle(X_train, y_train)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train[offset:end], y_train[offset:end]
sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
training_accuracy = evaluate(X_train, y_train)
validation_accuracy = evaluate(X_valid, y_valid)
print("EPOCH {} ...".format(i+1))
print("Training Accuracy = {:.3f}".format(training_accuracy))
print("Validation Accuracy = {:.3f}".format(validation_accuracy))
print()
test_accuracy = evaluate(X_test, y_test)
print("Test Accuracy = {:.3f}".format(test_accuracy))
print()
saver.save(sess, './lenet')
print("Model saved")
### We also plot bottom three least example images:
print("YUV example images:")
fg, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(10, 10))
ax1.imshow(train['features'][0])
ax1.set_title('RGB image')
ax2.imshow(yuv_image_data[:, :, 0], cmap='gray')
ax2.set_title('Y channel')
ax3.imshow(yuv_image_data[:, :, 1], cmap='gray')
ax3.set_title('U channel')
ax4.imshow(yuv_image_data[:, :, 2], cmap='gray')
ax4.set_title('V channel')
plt.setp([a.get_xticklabels() for a in fg.axes], visible=False)
plt.setp([a.get_yticklabels() for a in fg.axes], visible=False)
plt.show()
# The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file.
# Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug)
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
from models import DenseNet
from data_providers.utils import get_data_provider_by_name
import tensorflow as tf
train_params_cifar = {
'batch_size': 128,
'n_epochs': 100,
'initial_learning_rate': 0.01,
'reduce_lr_epoch_1': 50, # epochs * 0.5
'reduce_lr_epoch_2': 75, # epochs * 0.75
'validation_set': True,
'validation_split': None, # None or float
'shuffle': 'every_epoch', # None, once_prior_train, every_epoch
'normalization': 'by_chanels', # None, divide_256, divide_255, by_chanels
'use_Y': False, # use only Y channel
'data_augmentation': 0, # [0, 1]
}
import json
# We save this model params.json from the trained model
with open('model_params.json', 'r') as fp:
model_params = json.load(fp)
# some default params dataset/architecture related
train_params = train_params_cifar
print("Params:")
for k, v in model_params.items():
print("\t%s: %s" % (k, v))
print("Train params:")
for k, v in train_params.items():
print("\t%s: %s" % (k, v))
train_params['use_YUV'] = False
model_params['use_YUV'] = False
print("Prepare training data...")
data_provider = get_data_provider_by_name(model_params['dataset'], train_params)
print("Initialize the model..")
tf.reset_default_graph()
model = DenseNet(data_provider=data_provider, **model_params)
print("Loading trained model")
model.load_model()
print("Data provider test images: ", data_provider.test.num_examples)
print("Testing...")
loss, accuracy = model.test(data_provider.test, batch_size=30)
print("mean cross_entropy: %f, mean accuracy: %f" % (loss, accuracy))
total_prediction, y_test = model.predictions_test(data_provider.test, batch_size=100)
incorrectlist
import numpy as np
incorrectlist = []
for i in range(len(total_prediction)):
#if not correctness(y_test[i],total_prediction[i]):
for j in range(len(y_test[i])):
if not np.argmax(y_test[i][j]) == np.argmax(total_prediction[i][j]):
correct_classId = np.argmax(y_test[i][j])
predict_classId = np.argmax(total_prediction[i][j])
incorrectlist.append({'index':i*100+j, 'correct':correct_classId, 'predicted':predict_classId})
import pandas as pd
incorrectmatrix = {}
modeCount = 0
# get the label description from the CSV file.
classLabelList = pd.read_csv('signnames.csv')
for i in range(len(incorrectlist)):
predicted = incorrectlist[i]['predicted']
correct = incorrectlist[i]['correct']
index = incorrectlist[i]['index']
bucket = str(correct)+"+"+str(predicted)
incorrectinstance = incorrectmatrix.get(bucket, {'count': 0, 'samples':[]})
# add to the count
count = incorrectinstance['count'] + 1
# add to samples of this correct to predicted condition
samples = incorrectinstance['samples']
samples.append(index)
# put back in the list
incorrectmatrix[bucket] = {'count': count, 'correct':correct, 'predicted':predicted, 'samples':samples}
# update most common error
if count > modeCount:
modeCount = count
modeBucket = bucket
# get the list of buckets and sort them
def compare_bucket_count(bucket):
return modeCount-incorrectmatrix[bucket]['count']
sortedBuckets = list(incorrectmatrix.keys())
sortedBuckets.sort(key=compare_bucket_count)
# get the unique number of original picture sizes and the min and max last instance
n_buckets = len(sortedBuckets)
# print the stats
print("\nNumber of unique buckets in incorrect set: ", n_buckets, "\n")
print("Mode Bucket: ", modeBucket, "with count: ", modeCount)
print("\nTop Twenty Distribution of buckets with incorrect predicted test dataset labels:")
for n in range(20):
bucket = sortedBuckets[n]
cclassId = incorrectmatrix[bucket]['correct']
pclassId = incorrectmatrix[bucket]['predicted']
count = incorrectmatrix[bucket]['count']
cdescription = classLabelList[classLabelList.ClassId==cclassId].SignName.to_string(header=False,index=False)
pdescription = classLabelList[classLabelList.ClassId==pclassId].SignName.to_string(header=False,index=False)
print("incorrect set count: {0:4d} CClassId: {1:02d} Description: {2}\n PClassId: {3:02d} Description: {4}".format(count, cclassId, cdescription, pclassId, pdescription))
from matplotlib import pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline
from tqdm import tqdm
import random
import time
from matplotlib import gridspec
def draw_sample_incorrectmatrix(datasettxt, sortedBuckets, incorrectmatix, dataset, cmap=None):
n_samples = 11
n_labels = 10
# size of each sample
fig = plt.figure(figsize=(n_samples*1.8, n_labels))
w_ratios = [1 for n in range(n_samples)]
w_ratios[:0] = [int(n_samples*0.8)]
h_ratios = [1 for n in range(n_labels)]
# gridspec
time.sleep(1) # wait for 1 second for the previous print to appear!
grid = gridspec.GridSpec(n_labels, n_samples+1, wspace=0.0, hspace=0.0, width_ratios=w_ratios, height_ratios=h_ratios)
labelset_pbar = tqdm(range(n_labels), desc=datasettxt, unit='labels')
for a in labelset_pbar:
cclassId = incorrectmatrix[sortedBuckets[n_labels-a-1]]['correct']
pclassId = incorrectmatrix[sortedBuckets[n_labels-a-1]]['predicted']
cdescription = classLabelList[classLabelList.ClassId==cclassId].SignName.to_string(header=False,index=False)
pdescription = classLabelList[classLabelList.ClassId==pclassId].SignName.to_string(header=False,index=False)
count = incorrectmatrix[sortedBuckets[n_labels-a-1]]['count']
for b in range(n_samples):
i = a*(n_samples+1) + b
ax = plt.Subplot(fig, grid[i])
if b == 0:
ax.annotate('CClassId %d (%d): %s\nPClassId %d: %s'%(cclassId, count, cdescription, pclassId, pdescription), xy=(0,0), xytext=(0.0,0.3))
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
else:
random_i = random.choice(incorrectmatrix[sortedBuckets[n_labels-a-1]]['samples'])
image = dataset[random_i]
if cmap == None:
ax.imshow(image)
else:
# yuv = cv2.split(image)
# ax.imshow(yuv[0], cmap=cmap)
ax.imshow(image, cmap=cmap)
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
# We also plot the GT image on the right
i = a*(n_samples+1) + n_samples
ax = plt.Subplot(fig, grid[i])
img_idx = np.where(y_train==pclassId)
random_i = random.choice(img_idx[0])
image =X_train[random_i]
if cmap == None:
ax.imshow(image)
else:
ax.imshow(image, cmap=cmap)
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
# hide the borders\
if a == (n_labels-1):
all_axes = fig.get_axes()
for ax in all_axes:
for sp in ax.spines.values():
sp.set_visible(False)
plt.show()
draw_sample_incorrectmatrix('Test set 10 ten incorrect sample images using RGB as input, right most is the predicted image in the training set', sortedBuckets, incorrectmatrix, test['features'])
# The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file.
# Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug)
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
from models import DenseNet
from data_providers.utils import get_data_provider_by_name
import tensorflow as tf
import numpy as np
import json
import pandas as pd
from tqdm import tqdm
import random
import time
from matplotlib import pyplot as plt
# Visualizations will be shown in the notebook.
% matplotlib inline
from matplotlib import gridspec
# Load pickled data
import pickle
training_file = './data/train.p'
validation_file = './data/valid.p'
testing_file = './data/test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test_origin = test['features'], test['labels']
train_params_cifar = {
'batch_size': 64,
'n_epochs': 500,
'initial_learning_rate': 0.05,
'reduce_lr_epoch_1': 50, # epochs * 0.5
'reduce_lr_epoch_2': 75, # epochs * 0.75
'validation_set': True,
'validation_split': None, # None or float
'shuffle': 'every_epoch', # None, once_prior_train, every_epoch
'normalization': 'by_chanels', # None, divide_256, divide_255, by_chanels
'use_YUV': True,
'use_Y': False, # use only Y channel
'data_augmentation': 0, # [0, 1]
}
# We save this model params.json from the trained model
with open('model_params.json', 'r') as fp:
model_params = json.load(fp)
# some default params dataset/architecture related
train_params = train_params_cifar
print("Params:")
for k, v in model_params.items():
print("\t%s: %s" % (k, v))
print("Train params:")
for k, v in train_params.items():
print("\t%s: %s" % (k, v))
print("Prepare training data...")
data_provider = get_data_provider_by_name(model_params['dataset'], train_params)
print("Initialize the model..")
tf.reset_default_graph()
model = DenseNet(data_provider=data_provider, **model_params)
print("Loading trained model")
model.load_model()
print("Data provider test images: ", data_provider.test.num_examples)
print("Testing...")
loss, accuracy = model.test(data_provider.test, batch_size=30)
print("mean cross_entropy: %f, mean accuracy: %f" % (loss, accuracy))
total_prediction, y_test = model.predictions_test(data_provider.test, batch_size=100)
# Plotting incorrect examples
incorrectlist = []
for i in range(len(total_prediction)):
#if not correctness(y_test[i],total_prediction[i]):
for j in range(len(y_test[i])):
if not np.argmax(y_test[i][j]) == np.argmax(total_prediction[i][j]):
correct_classId = np.argmax(y_test[i][j])
predict_classId = np.argmax(total_prediction[i][j])
incorrectlist.append({'index':i*100+j, 'correct':correct_classId, 'predicted':predict_classId})
incorrectmatrix = {}
modeCount = 0
# get the label description from the CSV file.
classLabelList = pd.read_csv('signnames.csv')
for i in range(len(incorrectlist)):
predicted = incorrectlist[i]['predicted']
correct = incorrectlist[i]['correct']
index = incorrectlist[i]['index']
bucket = str(correct) + "+" + str(predicted)
incorrectinstance = incorrectmatrix.get(bucket, {'count': 0, 'samples': []})
# add to the count
count = incorrectinstance['count'] + 1
# add to samples of this correct to predicted condition
samples = incorrectinstance['samples']
samples.append(index)
# put back in the list
incorrectmatrix[bucket] = {'count': count, 'correct': correct, 'predicted': predicted, 'samples': samples}
# update most common error
if count > modeCount:
modeCount = count
modeBucket = bucket
# get the list of buckets and sort them
def compare_bucket_count(bucket):
return modeCount - incorrectmatrix[bucket]['count']
sortedBuckets = list(incorrectmatrix.keys())
sortedBuckets.sort(key=compare_bucket_count)
# get the unique number of original picture sizes and the min and max last instance
n_buckets = len(sortedBuckets)
# print the stats
print("\nNumber of unique buckets in incorrect set: ", n_buckets, "\n")
print("Mode Bucket: ", modeBucket, "with count: ", modeCount)
print("\nTop Twenty Distribution of buckets with incorrect predicted test dataset labels:")
for n in range(20):
bucket = sortedBuckets[n]
cclassId = incorrectmatrix[bucket]['correct']
pclassId = incorrectmatrix[bucket]['predicted']
count = incorrectmatrix[bucket]['count']
cdescription = classLabelList[classLabelList.ClassId == cclassId].SignName.to_string(header=False, index=False)
pdescription = classLabelList[classLabelList.ClassId == pclassId].SignName.to_string(header=False, index=False)
print(
"incorrect set count: {0:4d} CClassId: {1:02d} Description: {2}\n PClassId: {3:02d} Description: {4}".format(
count, cclassId, cdescription, pclassId, pdescription))
def draw_sample_incorrectmatrix(datasettxt, sortedBuckets, incorrectmatix, dataset, cmap=None):
n_samples = 11
n_labels = 10
# size of each sample
fig = plt.figure(figsize=(n_samples * 1.8, n_labels))
w_ratios = [1 for n in range(n_samples)]
w_ratios[:0] = [int(n_samples * 0.8)]
h_ratios = [1 for n in range(n_labels)]
# gridspec
time.sleep(1) # wait for 1 second for the previous print to appear!
grid = gridspec.GridSpec(n_labels, n_samples + 1, wspace=0.0, hspace=0.0, width_ratios=w_ratios,
height_ratios=h_ratios)
labelset_pbar = tqdm(range(n_labels), desc=datasettxt, unit='labels')
for a in labelset_pbar:
cclassId = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['correct']
pclassId = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['predicted']
cdescription = classLabelList[classLabelList.ClassId == cclassId].SignName.to_string(header=False, index=False)
pdescription = classLabelList[classLabelList.ClassId == pclassId].SignName.to_string(header=False, index=False)
count = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['count']
for b in range(n_samples):
i = a * (n_samples + 1) + b
ax = plt.Subplot(fig, grid[i])
if b == 0:
ax.annotate(
'CClassId %d (%d): %s\nPClassId %d: %s' % (cclassId, count, cdescription, pclassId, pdescription),
xy=(0, 0), xytext=(0.0, 0.3))
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
else:
random_i = random.choice(incorrectmatrix[sortedBuckets[n_labels - a - 1]]['samples'])
image = dataset[random_i]
if cmap == None:
ax.imshow(image)
else:
# yuv = cv2.split(image)
# ax.imshow(yuv[0], cmap=cmap)
ax.imshow(image, cmap=cmap)
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
# We also plot the GT image on the right
i = a * (n_samples + 1) + n_samples
ax = plt.Subplot(fig, grid[i])
img_idx = np.where(y_train == pclassId)
random_i = random.choice(img_idx[0])
image = X_train[random_i]
if cmap == None:
ax.imshow(image)
else:
ax.imshow(image, cmap=cmap)
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
# hide the borders\
if a == (n_labels - 1):
all_axes = fig.get_axes()
for ax in all_axes:
for sp in ax.spines.values():
sp.set_visible(False)
plt.show()
draw_sample_incorrectmatrix(
'Test set 10 ten incorrect sample images using RGB as input, right most is the predicted image in the training set',
sortedBuckets, incorrectmatrix, test['features'])
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import cv2
def labels_to_one_hot(labels, n_classes=43+1):
"""Convert 1D array of labels to one hot representation
Args:
labels: 1D numpy array
"""
new_labels = np.zeros((n_classes,))
new_labels[labels] = 1
return new_labels
def draw_sample_newimage_labels(datasettxt, labeldata, dataset, cmap=None):
n_maxsamples = 8
n_labels = len(labeldata)
# size of each sample
fig = plt.figure(figsize=(n_maxsamples*1.8, n_labels))
w_ratios = [1 for n in range(n_maxsamples)]
w_ratios[:0] = [int(n_maxsamples*0.8)]
h_ratios = [1 for n in range(n_labels)]
# gridspec
time.sleep(1) # wait for 1 second for the previous print to appear!
grid = gridspec.GridSpec(n_labels, n_maxsamples+1, wspace=0.0, hspace=0.0, width_ratios=w_ratios, height_ratios=h_ratios)
labelset_pbar = tqdm(range(n_labels), desc=datasettxt, unit='labels')
for a in labelset_pbar:
classId = labeldata[a]['label']
description = classLabelList[classLabelList.ClassId==classId].SignName.to_string(header=False,index=False)
count = labeldata[a]['count']
for b in range(n_maxsamples+1):
i = a*(n_maxsamples+1) + b
ax = plt.Subplot(fig, grid[i])
if b == 0:
ax.annotate('ClassId %d (%d): %s'%(classId, count, description), xy=(0,0), xytext=(0.0,0.5))
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
else:
if (b-1) < len(labeldata[a]['samples']):
image_rgb = dataset[labeldata[a]['samples'][b-1]]
image = image_rgb.copy()
image[:,:,0] = image_rgb[:,:,2]
image[:,:,2] = image_rgb[:,:,0]
if cmap == None:
ax.imshow(image)
else:
# yuv = cv2.split(image)
# ax.imshow(yuv[0], cmap=cmap)
ax.imshow(image, cmap=cmap)
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
# hide the borders\
if a == (n_labels-1):
all_axes = fig.get_axes()
for ax in all_axes:
for sp in ax.spines.values():
sp.set_visible(False)
plt.show()
newimages = []
newlabels = []
new_onehot = []
newlabelsdata = []
directories = "./newimages"
subdirs = os.listdir(directories)
for subdir in subdirs:
classId = int(subdir.split("-")[0])
classinfo = {'label':classId,'count':0, 'samples':[]}
filepath = directories+"/"+subdir
for filename in os.listdir(filepath):
image_filepath = filepath+"/"+filename
image = cv2.imread(image_filepath)
image = cv2.resize(image, (32, 32), interpolation=cv2.INTER_AREA)
newimages.append(image)
newlabels.append(classId)
new_onehot.append(labels_to_one_hot(classId))
classinfo['count'] += 1
classinfo['samples'].append(len(newimages)-1)
if classinfo['count'] > 0:
print("appending: ", classinfo)
newlabelsdata.append(classinfo)
newimages = np.array(newimages)
newlabels = np.array(newlabels)
new_onehot = np.array(new_onehot)
draw_sample_newimage_labels("New samples (RGB)", newlabelsdata, newimages)
print("done")
# The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file.
# Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug)
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
from models import DenseNet
from data_providers.utils import get_data_provider_by_name
import tensorflow as tf
import numpy as np
import json
import pandas as pd
from tqdm import tqdm
import random
import time
from matplotlib import pyplot as plt
# Visualizations will be shown in the notebook.
% matplotlib inline
from matplotlib import gridspec
# Load pickled data
import pickle
training_file = './data/train.p'
validation_file = './data/valid.p'
testing_file = './data/test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test_origin = test['features'], test['labels']
train_params_cifar = {
'batch_size': 64,
'n_epochs': 500,
'initial_learning_rate': 0.05,
'reduce_lr_epoch_1': 50, # epochs * 0.5
'reduce_lr_epoch_2': 75, # epochs * 0.75
'validation_set': True,
'validation_split': None, # None or float
'shuffle': 'every_epoch', # None, once_prior_train, every_epoch
'normalization': 'by_chanels', # None, divide_256, divide_255, by_chanels
'use_YUV': True,
'use_Y': False, # use only Y channel
'data_augmentation': 0, # [0, 1]
}
# We save this model params.json from the trained model
with open('model_params.json', 'r') as fp:
model_params = json.load(fp)
# some default params dataset/architecture related
train_params = train_params_cifar
print("Params:")
for k, v in model_params.items():
print("\t%s: %s" % (k, v))
print("Train params:")
for k, v in train_params.items():
print("\t%s: %s" % (k, v))
model_params['use_Y'] = False
print("Prepare training data...")
data_provider = get_data_provider_by_name(model_params['dataset'], train_params)
print("Initialize the model..")
tf.reset_default_graph()
model = DenseNet(data_provider=data_provider, **model_params)
print("Loading trained model")
model.load_model()
print("Data provider test images: ", data_provider.test.num_examples)
print("Testing...")
loss, accuracy = model.test(data_provider.test, batch_size=30)
import cv2
def labels_to_one_hot(labels, n_classes=43+1):
"""Convert 1D array of labels to one hot representation
Args:
labels: 1D numpy array
"""
new_labels = np.zeros((n_classes,))
new_labels[labels] = 1
return new_labels
newimages = []
newlabels = []
new_onehot = []
newlabelsdata = []
directories = "./newimages"
subdirs = os.listdir(directories)
for subdir in subdirs:
classId = int(subdir.split("-")[0])
classinfo = {'label':classId,'count':0, 'samples':[]}
filepath = directories+"/"+subdir
for filename in os.listdir(filepath):
image_filepath = filepath+"/"+filename
image = cv2.imread(image_filepath)
image_rgb = cv2.resize(image, (32, 32), interpolation=cv2.INTER_AREA)
image = image_rgb.copy()
image[:, :, 0] = image_rgb[:, :, 2]
image[:, :, 2] = image_rgb[:, :, 0]
newimages.append(image)
newlabels.append(classId)
new_onehot.append(labels_to_one_hot(classId))
classinfo['count'] += 1
classinfo['samples'].append(len(newimages)-1)
if classinfo['count'] > 0:
print("appending: ", classinfo)
newlabelsdata.append(classinfo)
newimages = np.array(newimages)
newlabels = np.array(newlabels)
new_onehot = np.array(new_onehot)
from data_providers.GermanTrafficSign import RGB2YUV
X_test_new = RGB2YUV(newimages)
new_image = np.zeros(X_test_new.shape)
for i in range(X_test_new.shape[-1]):
new_image[:, :, :, i] = ((X_test_new[:, :, :, i] - data_provider._means[i]) /data_provider._stds[i])
y_new_onehot = model.predictions_one_image(new_image)[0]
predict_classId = np.argmax(y_new_onehot, axis=1)
incorrectlist = []
for i in range(len(y_new_onehot)):
correct_classId = np.argmax(new_onehot[i],0)
predict_classId = np.argmax(y_new_onehot[i],0)
incorrectlist.append({'index':i, 'correct':correct_classId, 'predicted':predict_classId})
incorrectmatrix = {}
modeCount = 0
for i in range(len(incorrectlist)):
predicted = incorrectlist[i]['predicted']
correct = incorrectlist[i]['correct']
index = incorrectlist[i]['index']
bucket = str(correct) + "+" + str(predicted)
incorrectinstance = incorrectmatrix.get(bucket, {'count': 0, 'samples': []})
# add to the count
count = incorrectinstance['count'] + 1
# add to samples of this correct to predicted condition
samples = incorrectinstance['samples']
samples.append(index)
# put back in the list
incorrectmatrix[bucket] = {'count': count, 'correct': correct, 'predicted': predicted, 'samples': samples}
# update most common error
if count > modeCount:
modeCount = count
modeBucket = bucket
# get the list of buckets and sort them
def compare_bucket_count(bucket):
return modeCount - incorrectmatrix[bucket]['count']
sortedBuckets = list(incorrectmatrix.keys())
sortedBuckets.sort(key=compare_bucket_count)
# get the unique number of original picture sizes and the min and max last instance
n_buckets = len(sortedBuckets)
# print the stats
print("\nNumber of unique buckets in incorrect set: ", n_buckets, "\n")
print("Mode Bucket: ", modeBucket, "with count: ", modeCount)
classLabelList = pd.read_csv('signnames.csv')
print("\nDistribution of buckets with predicted test dataset labels:")
for n in range(len(sortedBuckets)):
bucket = sortedBuckets[n]
cclassId = incorrectmatrix[bucket]['correct']
pclassId = incorrectmatrix[bucket]['predicted']
count = incorrectmatrix[bucket]['count']
cdescription = classLabelList[classLabelList.ClassId == cclassId].SignName.to_string(header=False, index=False)
pdescription = classLabelList[classLabelList.ClassId == pclassId].SignName.to_string(header=False, index=False)
print(
"incorrect set count: {0:4d} CClassId: {1:02d} Description: {2}\n PClassId: {3:02d} Description: {4}".format(
count, cclassId, cdescription, pclassId, pdescription))
def draw_sample_correctmatrix(datasettxt, sortedBuckets, incorrectmatix, dataset, cmap=None):
n_maxsamples = 8
n_labels = len(sortedBuckets)
# size of each sample
fig = plt.figure(figsize=(n_maxsamples * 1.8, n_labels))
w_ratios = [1 for n in range(n_maxsamples)]
w_ratios[:0] = [int(n_maxsamples * 0.8)]
h_ratios = [1 for n in range(n_labels)]
# gridspec
time.sleep(1) # wait for 1 second for the previous print to appear!
grid = gridspec.GridSpec(n_labels, n_maxsamples + 1, wspace=0.0, hspace=0.0, width_ratios=w_ratios,
height_ratios=h_ratios)
labelset_pbar = tqdm(range(n_labels), desc=datasettxt, unit='labels')
row = 1
for i, a in enumerate(labelset_pbar):
cclassId = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['correct']
pclassId = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['predicted']
cdescription = classLabelList[classLabelList.ClassId == cclassId].SignName.to_string(header=False, index=False)
pdescription = classLabelList[classLabelList.ClassId == pclassId].SignName.to_string(header=False, index=False)
count = incorrectmatrix[sortedBuckets[n_labels - a - 1]]['count']
for b in range(n_maxsamples + 1):
i = a * (n_maxsamples + 1) + b
ax = plt.Subplot(fig, grid[i])
if b == 0:
ax.annotate(
'%d, CClassId %d (%d): %s\nPClassId %d: %s' % (row, cclassId, count, cdescription, pclassId, pdescription),
xy=(0, 0), xytext=(0.0, 0.3))
row += 1
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
else:
if (b - 1) < count:
image = dataset[incorrectmatrix[sortedBuckets[n_labels - a - 1]]['samples'][b - 1]]
if cmap == None:
ax.imshow(image)
else:
# yuv = cv2.split(image)
# ax.imshow(yuv[0], cmap=cmap)
ax.imshow(image, cmap=cmap)
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
# hide the borders\
if a == (n_labels - 1):
all_axes = fig.get_axes()
for ax in all_axes:
for sp in ax.spines.values():
sp.set_visible(False)
plt.show()
draw_sample_correctmatrix('prediction images (RGB)', sortedBuckets, incorrectmatrix, newimages)
### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
with tf.Session() as sess:
TOPKV = sess.run(tf.nn.top_k(tf.constant(y_new_onehot), k=5))
np.set_printoptions(precision=4)
np.set_printoptions(suppress=True)
print(TOPKV[0])
print(TOPKV[1])
n_labels = 43
newlabels = []
for i in range(n_labels):
newlabels.append(i)
ind = np.arange(n_labels)
# gridspec
time.sleep(1) # wait for 1 second for the previous print to appear!
grid = gridspec.GridSpec(n_labels, n_maxsamples + 1, wspace=0.0, hspace=0.0, width_ratios=w_ratios,
height_ratios=h_ratios)
w_ratios[:0] = [int(8 * 0.8)]
print(w_ratios)
fig = plt.figure(figsize=(20, len(newimages)))
w_ratios = [2, 2, 6]
h_ratios = [1 for n in range(len(newimages))]
grid = gridspec.GridSpec(ncols=3, nrows=len(newimages), wspace=0.0, hspace=0.0, width_ratios=w_ratios, height_ratios=h_ratios)
labelset_pbar = tqdm(range(len(newimages)), desc='Softmax Probabity', unit='labels')
time.sleep(1) # wait for 1 second for the previous print to appear!
np.set_printoptions(precision=2)
np.set_printoptions(suppress=True)
for a in labelset_pbar:
for b in range(3):
ax = fig.add_subplot(grid[a, b])
if b == 0:
x = TOPKV[0][a]
y = TOPKV[1][a]
anno_txt = (' '.join(['%.2f']*len(x))+"]") % tuple(x) + '\n ' + (' '.join(['%4d']*len(y))+"]") % tuple(y)
ax.annotate(anno_txt,xy=(0, 0), xytext=(0.0, 0.3))
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
elif b == 1:
image = newimages[a]
ax.imshow(image)
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
elif b == 2:
# fg, ax = plt.subplots(figsize=(n_labels/3, 3))
p1 = ax.bar(ind*1.15+0.75, y_new_onehot[a], width, color='b')
# add some text for labels, title and axes ticks
ax.set_ylim(0, 1)
#ax.set_title("Softmax Probabilities", fontsize=12)
#ax.set_xticks(ind*1.15 + 1.0)
#ax.set_xticklabels(newlabels, fontsize=10)
#ax.set_xlabel("Class Id", fontsize=12)
fig.add_subplot(ax, figsize=(n_labels/3, 3))
plt.show()
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.
Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.
For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.
Your output should look something like this (above)
first_conv_output = model.get_intermediate_output(new_image)[0]
activation = first_conv_output
activation_min = activation.min()
activation_max = activation.max()
featuremaps = activation.shape[3]
plt_num=8
plt.figure(plt_num, figsize=(15,15))
for featuremap in range(featuremaps):
plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
plt.imshow(activation[-1,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
activation_max